package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import bean.Ordine;

public class OrdineDAO extends DAO{

	private static OrdineDAO instance = null;
	private String SELECT = "select * from ordine";


	public static OrdineDAO getInstance() {
		if (instance == null)
			instance = new OrdineDAO();
		return instance;
	}
	
	public ArrayList<Ordine> getOrdini() throws SQLException {
		ResultSet rs = getManageConnection().getConnection().eseguiQuery(SELECT);
		
		ArrayList<Ordine> ordini = new ArrayList<Ordine>();
		while(rs.next()) {
			ordini.add(new Ordine(rs.getInt("id"), rs.getBoolean("evaso"), rs.getInt("id_tavolo"), rs.getInt("id_pietanza")));
		}
		return ordini;
		
	}
	
	public boolean insert(Object o) {
		Ordine ordine = (Ordine)o;
		String query = "insert into ordine (evaso, id_tavolo, id_pietanza) values("
		+ ordine.isEvaso() + ", "
		+ ordine.getId_tavolo() + ", "
		+ ordine.getId_pietanza() +")";
		
		return getManageConnection().getConnection().eseguiAggiornamento(query);
	}
	
	public boolean delete(int id_ordine) {
		String query = "delete from ordine where id="+ id_ordine;
		return getManageConnection().getConnection().eseguiAggiornamento(query);
	}
	
	public boolean update(Object o) {
		Ordine ordine = (Ordine)o;
		String query = "update ordine set " +
				"evaso=" + ordine.isEvaso() + ", " +
				"id_tavolo=" + ordine.getId_tavolo() + ", " +
				"evaso=" + ordine.getId_pietanza() +
				" where id="+ ordine.getId();
		return getManageConnection().getConnection().eseguiAggiornamento(query);
	}
	
	public Object findById(Object o) {
		String query = SELECT + " and id = " + ((Integer)o).intValue();
		Ordine ordine = new Ordine();
		try {
			ResultSet rs = getManageConnection().getConnection().eseguiQuery(query);
			
			if (rs.next()) 
				ordine = new Ordine(rs.getInt("id"), rs.getBoolean("evaso"), rs.getInt("id_tavolo"), rs.getInt("id_pietanza"));

		} catch (Exception e) {
			e.printStackTrace();
		}
		return (Object)ordine;

		
	}
	
}
		